package com.syh.jn.scm.infrastructure.repository.impl.operation.system;

import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.core.ddd.infrastructure.repository.AbstractAggregateRepository;
import com.syh.jn.scm.domain.operation.entity.system.PermissionType;
import com.syh.jn.scm.domain.operation.repository.system.PermissionTypeRepository;
import com.syh.jn.scm.dto.operation.system.permission.PermissionTypeVo;
import com.syh.jn.scm.infrastructure.repository.model.system.PermissionTypeModel;
import com.syh.jn.scm.infrastructure.repository.utils.SQLAliasGenerateUtil;
import com.syh.jn.scm.infrastructure.wrapper.BaseResolve;
import com.syh.jn.scm.infrastructure.wrapper.ResolveToSQL;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class PermissionTypeRepositoryImpl extends AbstractAggregateRepository<PermissionType,PermissionTypeModel,Long>  implements PermissionTypeRepository {


	@Override
	public List<PermissionType> getAllSystemTypeNames() {
		String hql="FROM PermissionTypeModel model GROUP BY systemType";
		List<PermissionTypeModel> result=this.hibernateTemplate.getSessionFactory().getCurrentSession().createQuery(hql).list();
		return this.transform(result);
	}

	@Override
	public void batchDiscardPermissionTypes(List<Long> ids) {
		String hql = "UPDATE PermissionTypeModel SET del=-1  WHERE id in (:ids)";
		this.hibernateTemplate.getSessionFactory().getCurrentSession().createQuery(hql).setParameterList("ids", ids).executeUpdate();
	}

	@Override
	protected SQL getViewSql() {
		return new SQL() {{
			SELECT(
							SQLAliasGenerateUtil.aliasGenerate(PermissionTypeModel.class,"per",null),
							"super.PERMISSION_TYPE_NAME AS supPermissionTypeName",
							"super.TERMINAL_TYPE AS supTerminalType"
			);
			FROM("T_SYSTEM_PERMISSION_TYPE per");
			LEFT_OUTER_JOIN("T_SYSTEM_PERMISSION_TYPE super ON per.SUPER_ID = super.ID");
		}};
	}
	@Override
	protected Class getViewObject() {
		return PermissionTypeVo.class;
	}

	@Override
	protected BaseResolve getViewWrapperResolve(Wrapper wrapper) {
		Map<String,String> params = new HashMap<>();
		params.put("superId","per.SUPER_ID");
		params.put("id","per.ID");
		params.put("terminalType","per.TERMINAL_TYPE");
		params.put("del", "per.DEL");
		params.put("permissionTypeName","per.PERMISSION_TYPE_NAME");
		ResolveToSQL parse = new ResolveToSQL(wrapper, (propertyName) -> {
			return params.get(propertyName);
		});
		return parse;
	}

}
